package com.zzyl.job;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.json.JSONUtil;
import com.zzyl.constant.CacheConstants;
import com.zzyl.entity.AlertRule;
import com.zzyl.mapper.AlertRuleMapper;
import com.zzyl.service.AlertRuleService;
import com.zzyl.vo.DeviceDataVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * 设备上报数据报警规则过滤
 */
@Component
public class AlertJob {

    @Autowired
    private AlertRuleMapper alertRuleMapper;
    @Autowired
    private RedisTemplate<String,String> redisTemplate;
    @Autowired
    private AlertRuleService alertRuleService;

    /**
     * 设备上报数据报警规则过滤
     * 周期：每隔一分钟执行一次
     */
    @Scheduled(cron = "0 * * * * ?")
    public void deviceDataAlertFilter(){
        //1.查询所有的报警规则
        List<AlertRule> alertRules = alertRuleMapper.selectByFunctionId(null, null, null);
        if(CollUtil.isEmpty(alertRules)){
            return;
        }
        //2.查询所有设备的上报数据  判断
        List<Object> jsonStrList = redisTemplate.opsForHash().values(CacheConstants.IOT_DEVICE_LAST_DATA_KEY);
        if(CollUtil.isEmpty(jsonStrList)){
            return;
        }
        //3.数据格式标准化处理   不为空
        List<DeviceDataVo> deviceDataVoList = new ArrayList<>();
        jsonStrList.forEach(json -> deviceDataVoList.addAll(JSONUtil.toList(json.toString(),DeviceDataVo.class)));
        //4.对每一条设备上的数据（属性）进行报警规则校验
        deviceDataVoList.forEach(d -> alertRuleService.alertFilter(d));
    }
}
